class MaterialPlayer {
  lastTask = null
  audio = document.createElement('AUDIO')
  load(url, time, success, ended) {
    if (this.lastTask) {
      this.destroyLastTask()
    }
    this.lastTask = {
      success: success,
      ended: ended,
      timeUpdate: this.timeUpdate,
      seekTime: time,
      loaded: false
    }
    this.audio.src = url
    this.audio.autoplay = false
    // this.audio.addEventListener('play', this.lastTask.success, false)
    this.audio.addEventListener('ended', this.lastTask.ended, false)
    this.audio.addEventListener('timeupdate', this.lastTask.timeUpdate, false)
    this.audio.play()
    this.audio.currentTime = this.lastTask.seekTime
  }
  timeUpdate = () => {
    if (this.lastTask.loaded) {
      return
    }
    if (this.audio.currentTime > this.lastTask.seekTime) {
      this.audio.pause()
      this.lastTask.loaded = true
      this.lastTask && this.lastTask.success && this.lastTask.success()
    }
  }
  destroyLastTask() {
    this.audio.pause()
    this.audio.removeEventListener('ended', this.lastTask.ended, false)
    this.audio.removeEventListener('timeupdate', this.lastTask.timeUpdate, false)
  }
  stop() {
    if (this.lastTask) {
      this.destroyLastTask()
    }
  }
  start() {
    try {
      this.audio.play()
    } catch (e) {}
  }
  pause() {
    try {
      this.audio.pause()
    } catch (e) {}
  }
  getCurrentTime() {
    var time = 0
    try {
      time = this.audio.currentTime
    } catch (e) {}
    return time
  }
}
module.exports = new MaterialPlayer()
